package br.com.skolar.client.framework;

import java.util.ArrayList;
import java.util.HashMap;

import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class EventBus extends HandlerManager {
	private HashMap<Class<? extends Event>, ArrayList<Event.Handler>> handlers = new HashMap();
	
	@Inject
	public EventBus() {
		super(null);
		addHandler(Event.TYPE, new Event.Handler() {
			@Override
			public void onEvent(Event e) {
				Class c = e.getClass();
				ArrayList<Event.Handler> handlerList = handlers.get(c);
				if (handlerList==null)
					Window.alert("No handler for " + c.getName());
				else for (Event.Handler h : handlerList)
					h.onEvent(e);
			}
		});
	}
	
	public<C extends Event> void addHandler(Class<C> c, Event.Handler<C> h) {
		ArrayList list = handlers.get(c);
		if (list==null) {
			list = new ArrayList();
			handlers.put(c, list);
		}
		list.add(h);
	}
}